<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'

let config = ref({
    isFixed: false,
    isTop: false,
    isTransparent: false
})

let colElms = ref([])
let lastSec = ref(new Date().getSeconds())
let timerId = ref(null)

//
function getTimeStr(date = new Date()) {
    return [date.getHours(), date.getMinutes(), date.getSeconds()]
        .map((item) => item.toString().padStart(2, '0'))
        .join('')
}

// 创建时钟列
function createCol() {
    const createEl = (cls) => {
        const div = document.createElement('div')
        div.classList.add(cls)
        return div
    }
    const [col, flip, flipNext, flipCurr, next, curr] = [
        'col',
        'flip',
        'next',
        'curr',
        'next',
        'curr'
    ].map((cls) => createEl(cls))
    flip.append(flipNext, flipCurr)
    col.append(flip, next, curr)
    document.getElementById('time').append(col)
    return {
        toggleActive: () => flip.classList.toggle('active'),
        getCurr: () => curr.dataset.t,
        setCurr: (t) => [flipCurr, curr].forEach((el) => (el.dataset.t = t)),
        setNext: (t) => [flipNext, next].forEach((el) => (el.dataset.t = t))
    }
}

// 更新时间和运行动画逻辑保持不变...
function updateTime() {
    let s = new Date().getSeconds()
    if (s === lastSec.value) {
        return
    }
    lastSec.value = s
    const currStr = getTimeStr()
    colElms.value.forEach(({ toggleActive, getCurr, setCurr, setNext }, i) => {
        var currTxt = getCurr()
        setNext(currStr[i])
        if (currTxt !== currStr[i]) {
            toggleActive()
            setTimeout(() => {
                toggleActive()
                setCurr(currStr[i])
            }, 500)
        }
    })
}
function run() {
    updateTime()
    setTimeout(() => {
        run()
    }, 1000 / 60)
}
watch(
    config,
    (newValue, oldValue) => {
        console.log(newValue, oldValue)
        console.log(newValue, 'config变动啦')

        localStorage.setItem('config', JSON.stringify(newValue))
    },
    { deep: true }
)

let datestr = ref('')
onMounted(() => {
    let config_local = localStorage.getItem('config')

    if (config_local) {
        config.value = JSON.parse(config_local)
    } else {
        localStorage.setItem('config', JSON.stringify(config.value))
    }

    // 初始化时钟
    const date = new Date()
    datestr.value =
        date.getFullYear() +
        '年' +
        (date.getMonth() + 1) +
        '月' +
        date.getDate() +
        '日 ' +
        getDays()

    for (let i = 0; i < 6; i++) {
        colElms.value.push(createCol())
    }
    console.log(colElms.value)

    const timeStr = getTimeStr()
    colElms.value.forEach(({ setCurr }, i) => {
        setCurr(timeStr[i])
    })
    run()
})

onUnmounted(() => {
    if (timerId.value) clearTimeout(timerId)
})

let container = ref(null)

function changeFlex() {
    window.ipcRenderer.send('window-fixed', !config.value.isFixed)
    const e = container.value

    if (!config.value.isFixed) {
        e.classList.add('no-drag')
    } else {
        e.classList.remove('no-drag')
    }
    config.value.isFixed = !config.value.isFixed
}

function getDays() {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return days[new Date().getDay()]
}

function changeTop() {
    window.ipcRenderer.send('window-top', !config.value.isTop)
    config.value.isTop = !config.value.isTop
}
function changeTransparent() {
    window.ipcRenderer.send('window-transparent', !config.value.isTransparent)
    reSize()
    config.value.isTransparent = !config.value.isTransparent
}
function close() {
    window.ipcRenderer.send('window-close')
}

let isConfig = ref(true)

function showConfig() {
    const e = container.value
    isConfig.value = !isConfig.value
    e.classList.add('body-broder')
    if (!config.value.isTransparent) {
        e.classList.remove('body-broder')
    }
}
let el = ref({
    w: 0,
    h: 0
})
watch(
    el,
    (newValue, oldValue) => {
        console.log(newValue, oldValue)
        window.ipcRenderer.send('window-size', JSON.stringify(newValue))
    },
    { deep: true }
)
function reSize() {
    const e = container.value
    el.value.w = e.clientWidth
    el.value.h = Math.floor((e.clientWidth * 4) / 9)
}

document.addEventListener('keydown', (event) => {
    // 检测是否同时按下Ctrl + Shift + I,自动打开开发者模式
    if (event.ctrlKey && event.shiftKey && event.key === 'I') {
        // 阻止默认行为
        event.preventDefault()

        // 导入electron的进程通信API
        const { ipcRenderer } = require('electron')
        // 设置应用的控制台打开/关闭
        ipcRenderer.send('SET_CONSOLE')
    }
})
</script>

<template>
    <div
        class="container"
        ref="container"
    >
        <div
            class="config"
            v-if="isConfig"
        >
            <div class="cfg-item">
                时钟设置：
                <i
                    @click="changeFlex"
                    title="固定在屏幕上"
                    class="iconfont icon-left"
                    :class="config.isFixed ? 'active' : ''"
                ></i>
                <i
                    @click="changeTop"
                    title="置顶"
                    class="iconfont icon-zhiyudingceng"
                    :class="config.isTop ? 'active' : ''"
                ></i>
                <i
                    @click="changeTransparent"
                    title="窗口设置"
                    class="iconfont icon-chuangkoudaxiao"
                    :class="config.isTransparent ? 'active' : ''"
                ></i>
                <i
                    class="iconfont icon-guanbi"
                    title="关闭"
                    @click="close"
                ></i>
            </div>
        </div>
        <div
            id="time"
            class="time"
            :class="config.isFixed? 'no-drag' : 'drag'"
        >
        </div>

        <div
            class="date"
            :class="config.isFixed? 'no-drag' : 'drag'"
            @click="showConfig"
            title="配置"
        >{{ datestr  }}<span>" By: Mr.Zhang"</span></div>
    </div>
</template>

<style lang="css">
:root {
    --body-bg: #333; /* 网页背景颜色 */
    --font-size: 15vw; /* 时钟字体大小 */
    --center-border: 0.3vw solid #000; /* 翻页中间的边框色 */
    --col-width: 13vw; /* 6个时间块的宽度 */
    --col-height: 23vw; /* 时钟高度 */
    --col-color: #ddd; /* 时钟字体颜色 */
    --col-bg: #1a1a1a; /* 时钟背景色 */
}

body {
    -webkit-app-region: drag;
}
.body-broder {
    border: 1px solid rgba(0, 0, 0, 0.3);
}

.container {
    -webkit-app-region: drag;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 1vw;
    padding: 0.2vw;
}

.config {
    background: rgba(0, 0, 0, 0.1);
    border-radius: 0.2vw;
    width: 92%;
    height: 5vw;
    opacity: 0.8;
    color: #000;
    font-size: 2vw;
    font-weight: 600;
    text-shadow: 0.2vw 0.2vw 0 white;
    display: flex;
    justify-content: flex-end;
}
.cfg-item {
    margin-left: auto;
    display: flex;
    align-items: center;
    font-weight: 400;
    justify-content: flex-end;
    text-shadow: none;
    gap: 5px;
    -webkit-app-region: no-drag;
}
.cfg-item i {
    font-size: 2.4vw;
    cursor: pointer;
    color: #fff;
    background: #999;
    border: 0.2vw solid #666;
    padding: 1vw;
}
.cfg-item i:hover,
.cfg-item .active {
    background: #000;
    color: #fff;
}

.drag {
    /* 设置该属性表明这是可拖拽区域，用来移动窗口 */
    -webkit-app-region: drag;
}

.no-drag {
    -webkit-app-region: no-drag;
}

.time {
    justify-content: center;
    align-items: center;
    display: flex;
    gap: 1vw;
    opacity: 0.8;
    font-family: sans-serif;
    font-weight: 700;
    overflow: hidden;
}

.col {
    width: var(--col-width);
    height: var(--col-height);
    perspective: var(--col-height);
}
.col:nth-child(3),
.col:nth-child(5) {
    margin-left: 3vw;
}

.curr,
.next {
    position: relative;
    width: var(--col-width);
    height: calc(var(--col-height) / 2);
    font-size: var(--font-size);
    background: var(--col-bg);
    border-radius: 1vw;
    color: var(--col-color);
    overflow: hidden;
    box-sizing: border-box;
}

.flip .curr::before,
.flip .next::before,
.col > .curr::before,
.col > .next::before {
    position: absolute;
    content: attr(data-t);
    line-height: var(--col-height);
    text-align: center;
    height: var(--col-height);
    left: 0;
    right: 0;
}

.flip .curr::before,
.col > .next::before {
    top: 0;
}

.flip .next::before,
.col > .curr::before {
    bottom: 0;
}

.flip .curr,
.col > .next {
    border-bottom: var(--center-border);
}

.flip .next,
.col > .curr {
    border-top: var(--center-border);
}

.flip .next {
    transform: rotateX(-180deg);
    backface-visibility: hidden;
}

.flip .curr {
    position: absolute;
    top: 0;
    backface-visibility: hidden;
}

.flip {
    position: absolute;
    width: var(--col-width);
    height: var(--col-height);
    z-index: 1;
    transform-style: preserve-3d;
    transition: transform 0s;
    transform: rotateX(0);
}

.flip.active {
    transition: all 0.5s ease-in-out;
    transform: rotateX(-180deg);
}

.date {
    width: 100%;
    top: 32vw;
    background: #87eba5;
    border-radius: 1vw;
    line-height: 6vw;
    font-size: 3vw;
    text-align: center;
    color: #333;
    font-weight: 700;
    font-family: 'Microsoft YaHei';
    cursor: pointer;
    user-select: none;
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE 10及更高版本 */
    -webkit-app-region: no-drag;
}
.date span {
    margin-left: 3vw;
    font-size: 2.4vw;
    font-weight: 400;
    color: #666;
}
</style>
